<template>
  <div class="yy-page yy-base-employee">
    <div class="yy-page-search" v-if="showSearch">
      <WidgetForm ref="searchFormWidget" :option="{
        style: 'display: flex;',
        itemStyle: 'margin-right: 10px;margin-bottom: 0;align-items: center;'
      }" :form-fields="search.formFields" :form-buttons="search.formButtons" />
    </div>
    <div class="yy-page-header">
      <div class="yy-page-header_title">
        <el-button  plain icon="Plus" type="primary" @click="onOpenDialog()">新增</el-button>
      </div>
      <div class="yy-page-header_action">
        <right-toolbar @showSearch="onShowSearch" @queryTable="getCategoryList"></right-toolbar>
      </div>
    </div>
    <div class="yy-page-data">
       <WidgetTable  ref="tableDataRef" :is-loading="table.isLoading" :columns="table.columns" :data="table.data" :formats="table.formats" :paging-data="table.paging"></WidgetTable>
    </div>

    <WidgetFormDialog ref="widgetFormDialogRef"
                      :form-fields="dialog.formFields"
                      :model-instance="dialog.modelInstance"
                      :save-api-fun="dialog.saveApiFun"
                      :update-api-fun="dialog.updateApiFun"
                      :option="{
                      businessName: '员工',
                    }"
                      @edit-callback="onEditCallback"
    />
  </div>
</template>

<script setup lang="ts">

import {onBeforeMount, reactive, ref} from "vue";
import {TableColumn, WidgetFormField} from "@/model/Definition";
import {BaseModel} from "@/model/BaseModel";
import {formatDate} from "@/utils/yayi";
import EmployeeApi from "@/api/system/empl";
import {EmployeeModel} from "@/model/EmployeeModel";
import {getDictsByMultiType} from '@/api/system/dict/data'
import {DictDataModel} from "@/model/DictDataModel";
import {DictEnum} from "@/model/DictTypeModel";
import WidgetTable from "@/components/widget/WidgetTable.vue";
import WidgetFormDialog from "@/components/widget/WidgetFormDialog.vue";
import WidgetForm from "@/components/widget/WidgetForm.vue";

let dictItems: DictDataModel[] = []
const showSearch = ref(true)
const dialog = reactive<{formFields: WidgetFormField[],modelInstance: BaseModel, saveApiFun: any, updateApiFun: any}>({
  modelInstance: new EmployeeModel(),
  saveApiFun: EmployeeApi.saveEmployee,
  updateApiFun: EmployeeApi.updateEmployee,
  formFields: [
    {field: 'photo', label: '头像', type: 'avatar', placeholder: '请选择头像'},
    {field: 'name', label: '名称', type: 'text', placeholder: '请输入名称', required: [{required: true, message: '员工名称不能为空', trigger: 'blur'}]},
    {field: 'code', label: '代码', type: 'text', placeholder: '请输入代码', required: [{required: true, message: '员工代码不能为空', trigger: 'blur'}]},
    {field: 'sex', label: '性别', type: 'radioGroup', initVal: 1, options: EmployeeModel.SexMap},
    {
      field: 'typeCode', label: '类型', initVal: 'D', type: 'radioGroup', options: EmployeeModel.TypeMap,
      atChange: (val, fieldObj) => {
        const typeCodeField = dialog.formFields.find(item => item.field === 'typeCode')
        //todo 以后优化 级联： levelCode， 根据该initVal字段重新计算列表
        typeCodeField.initVal = val
        widgetFormDialogRef.value.setFieldValue('typeName',  EmployeeModel.getType(val).label)
      }
    },
    {field: 'typeName', label: '名称',
      initVal: () => {
        const codeField = dialog.formFields.find(item => item.field === 'typeCode')
        return EmployeeModel.getType(codeField.initVal).label
      }, type: 'text', placeholder: '请输入名称', hide: true
    },
    {field: 'levelCode', label: '职级', type: 'select', placeholder: '请选择员工职级',
      config: {
        select: {
          filterable: true, remote: true,
          remoteShowSuffix: true,
          remoteMethod: (searchKey: string)=> {
            const typeCodeField = dialog.formFields.find(item => item.field === 'typeCode');
            const doctorLevelItems = dictItems.filter(item => item.dictType === DictEnum.SYSTEM_DOCTOR_LEVEL);
            const nurseLevelItems = dictItems.filter(item => item.dictType === DictEnum.SYSTEM_NURSE_LEVEL);
            const options = typeCodeField.initVal === 'D' ?doctorLevelItems.map(item => Object.assign({
              label:  item.dictLabel,
              value: item.dictValue
            })) : nurseLevelItems.map(item => Object.assign({
              label:  item.dictLabel,
              value: item.dictValue
            }))
            const formField = dialog.formFields.find(item => item.field === 'levelCode')
            formField.options = options
          }
        }
      },
      atChange: (val) => {
        const typeCodeField = dialog.formFields.find(item => item.field === 'typeCode');
        const doctorLevelItems = dictItems.filter(item => item.dictType === DictEnum.SYSTEM_DOCTOR_LEVEL);
        const nurseLevelItems = dictItems.filter(item => item.dictType === DictEnum.SYSTEM_NURSE_LEVEL);
        if (typeCodeField.initVal === 'D') {
          const levelItem = doctorLevelItems.find(item => item.dictValue === val)
          if (levelItem) {
            widgetFormDialogRef.value.setFieldValue('levelName', levelItem.dictLabel)
          }
        } else {
          const levelItem = nurseLevelItems.find(item => item.dictValue === val)
          if (levelItem) {
            widgetFormDialogRef.value.setFieldValue('levelName', levelItem.dictLabel)
          }
        }
      }
    },
    {field: 'levelName', label: '名称', type: 'text', placeholder: '请输入名称', hide: true},
    {field: 'eduCode', label: '教育程度', type: 'select', placeholder: '请选择员工职级', options: [],
      atChange: (val) => {
        const eduItem = dictItems.find(item => item.dictType === DictEnum.SYSTEM_COMMON_EDU && item.dictValue === val);
        if (eduItem) {
          widgetFormDialogRef.value.setFieldValue('eduName', eduItem.dictLabel)
        }
      }
    },
    {field: 'eduName', label: '名称', type: 'text', placeholder: '请输入名称', hide: true},
    {field: 'birthday', label: '出生日期', type: 'date', placeholder: '请选择出生日期'},
    {field: 'phone', label: '联系方式', type: 'text', placeholder: '请输入联系电话'},
    {field: 'keywords', label: '检索码', type: 'text', placeholder: '请输入检索码'},
    {field: 'ability', label: '擅长', type: 'textarea', placeholder: '请输入医生特长'},
    {field: 'remark', label: '简介', type: 'textarea', placeholder: '请输入医生简介'},
    {field: 'state', label: '状态', type: 'radioGroup', initVal: 1, options: [{label: '启用', value: 1}, {label: '停用', value: 0}]}
  ]
})

const search = reactive<{formFields: WidgetFormField[],formData: any, formButtons: any, modelInstance: BaseModel, searchApiFun:any}>({
    modelInstance: new EmployeeModel(),
    searchApiFun: EmployeeApi.listEmployee,
    formData: {},
    formFields: [
      {field: 'searchKey', config: {input: {clearable: true}}, placeholder:"请输入名称或编码的关键字", label: '关键字', type: 'text', style:'width: 200px;',},
      {field: 'state', config:{select: {clearable: true}}, label: '状态', type: 'select', initVal: -1, style:'width: 100px;', options: [{label: '全部', value: -1},{label: '启用', value: 1}, {label: '停用', value: 0}]}
    ],
    formButtons: [
      {type: 'primary', label:'搜索', icon: 'search', atClick: ()=> {
          const formData = searchFormWidget.value.getFormFieldValue()
          search.formData = Object.assign({}, formData, {searchKey: formData.searchKey?.length ? formData.searchKey : null, state: formData.state === -1 ? null : formData.state})
          getCategoryList(1)
        }
      },
      {type: 'default', label: '清空', icon: 'refresh', atClick: () => {
          searchFormWidget.value.resetFields()
        }
      }
    ]
})

const table = reactive<{
  isLoading: boolean,
  paging: any,
  columns: TableColumn[],
  data: EmployeeModel[],
  formats?: any
}>({
  isLoading: false,
  columns: [
    {
      "field":"index",
      "label":"序号",
      "type": "index",
      "showable":true,
      "align": 'center',
      "width": 60,
      "fixed": 'left'
    },
    {
      "field":"name",
      "label":"名称",
      "showable":true,
      "fixed": 'left'
    },
    {
      "field":"code",
      "label":"编码",
      "showable":true
    },
    {
      "field":"sex",
      "label":"性别",
      "showable":true
    },
    {
      "field":"birthday",
      "label":"出生日期",
      "showable":true
    },
    {
      "field":"phone",
      "label":"联系电话",
      "showable":true
    },
    {
      "field":"levelName",
      "label":"职级",
      "showable":true
    },
    {
      "field":"eduName",
      "label":"教育程度",
      "showable":true
    },
    {
      "field":"typeCode",
      "label":"类型",
      "showable":true
    },
    {
      "field":"ability",
      "label":"擅长",
      "showable":true,
      width: 200
    },
    {
      "field":"remark",
      "label":"医生简介",
      "showable":true,
      width: 200
    },
    {
      "field":"keywords",
      "label":"检索码",
      "showable":true,
    },
    {
      "field":"updateName",
      "label":"更新用户",
      "showable":true,
      "width": 120
    },
    {
      "field":"updateTime",
      "label":"更新时间",
      "showable":true,
      "width": 140
    },
    {
      "field":"state",
      "label":"状态",
      "showable":true,
      "sortable":false,
      "align": 'center',
      "width": 60,
      "fixed": 'right'
    },
    {
      "field":"action",
      "label":"操作",
      "width": 150,
      "showable":true,
      "sortable":false,
      "align": 'center',
      "fixed": 'right'
    }
  ],
  paging: {
    isPaging: true,
    pageSize: 30,
    pageIndex: 1,
    total: 0,
    pageChange: (pageIndex: number) => {
      onPageChange(pageIndex)
    }
  },
  data: [],
  formats: {
    'state': {
      textType:'text',
      typeFormat: EmployeeModel.getStateType,
      labelFormat: EmployeeModel.getStateLabel
    },
    'sex': {
      labelFormat: (sex, row) => EmployeeModel.getSex(sex)?.label
    },
    'birthday': {
      labelFormat: (val, row) => val ? formatDate(val, 'YYYY-MM-DD') : ''
    },
    'typeCode': {
      labelFormat: (val, row) => EmployeeModel.getType(val)?.label
    },
    'updateTime': {
      labelFormat:  (val) =>formatDate(val)
    },
    'action': {
      items: [
        {label: '编辑',elType: 'button', value: 'edit', atClick: (data: EmployeeModel) => onOpenDialog(data)},
        {label: '删除',elType: 'button', value: 'delete',  confirm: {title: '您确定要删除该员工吗？', atConfirm: (data: EmployeeModel) => onDeleteCategory(data)}}
      ]
    }
  }
})
const searchFormWidget = ref()
const widgetFormDialogRef = ref()
const tableDataRef = ref()

onBeforeMount(() => {
  getEmployeeDict()
  getCategoryList(table.paging.pageIndex)
})

const onShowSearch = () => {
  showSearch.value = !showSearch.value
  tableDataRef.value.onWindowResize()
}
const getCategoryList = (pageIndex = 1) => {
  table.isLoading = true
  EmployeeApi.listEmployee(search.formData.searchKey, search.formData.state, pageIndex, table.paging.pageSize).then((pagingData) => {
    table.data = pagingData.data
    table.paging = Object.assign({}, table.paging, {
      pageIndex: pagingData.pageIndex,
      total: pagingData.total
    })
    table.isLoading = false
  }, () => {
    table.isLoading = false
  })
}

const onOpenDialog = (data?: EmployeeModel) => {
  if (data) {
    const formField = dialog.formFields.find(item => item.field === 'levelCode')
    formField.options = [{label: data.levelName, value: data.levelCode}]
  }
  widgetFormDialogRef.value.onShowDialog(data)
}


/**
 * 查询员工相关字典
 */
const getEmployeeDict = () => {
  getDictsByMultiType([DictEnum.SYSTEM_DOCTOR_LEVEL, DictEnum.SYSTEM_NURSE_LEVEL,DictEnum.SYSTEM_COMMON_EDU]).then((data) => {
    dictItems = data.data
    const options =  dictItems.filter(item => item.dictType === DictEnum.SYSTEM_COMMON_EDU).map(item => Object.assign({
      label: item.dictLabel,
      value: item.dictValue
    }))
    const formField = dialog.formFields.find(item => item.field === 'eduCode')
    formField.options = options
  })
}

const onDeleteCategory = (data: EmployeeModel) => {
  EmployeeApi.deleteEmployee(data.id).then(() => {
    const index = table.data.findIndex(item => item.id === data.id);
    if (index >= 0) {
      table.paging = Object.assign({}, table.paging, {
        total: table.paging.total - 1
      })
      table.data.splice(index, 1)
    }
  })
}

const onPageChange = (pageIndex: number) => {
  if (pageIndex != table.paging.pageIndex) {
    getCategoryList(pageIndex);
  }
}

const onEditCallback = (data: EmployeeModel) => {
  const index = table.data.findIndex(item => item.id === data.id);
  if (index < 0) {
    table.data.unshift(data)
    table.paging = Object.assign({}, table.paging, {
      total: table.paging.total + 1
    })
  } else {
    table.data.splice(index, 1, data)
  }
}
</script>
<style scoped lang="scss">
.yy-base-employee {
  height: 100%;
}
</style>